package org.wlgzs.moyue.service.servicelmpl;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;
import org.wlgzs.moyue.dao.LoginDao;
import org.wlgzs.moyue.dao.UserDao;
import org.wlgzs.moyue.entity.Login;
import org.wlgzs.moyue.entity.User;
import org.wlgzs.moyue.service.LoginService;
import org.wlgzs.moyue.util.AuthUtils;
import org.wlgzs.moyue.util.Result;
import org.wlgzs.moyue.util.ResultCode;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private LoginDao loginDao;
    @Autowired
    private UserDao userDao;

    public Result insideLogin(Login login, HttpSession session) {
        Login login1 = loginDao.getLoginByIdentityAndCertificate(login.getIdentity(), login.getCertificate());
        if (login1 != null) {
            User user = userDao.findById(login1.getUserId()).get();
            session.setAttribute("user", user);
            if (user.getRoleId().equals("4"))return new Result(ResultCode.ADMIN);
            return new Result(ResultCode.SUCCESS);
        }
        return new Result(ResultCode.FAIL);
    }

    public Result deleteLogin(long loginId, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (loginDao.existsById(loginId) && loginDao.findById(loginId).get().getUserId() == user.getUserId()) {
            loginDao.deleteById(loginId);
            return new Result(ResultCode.SUCCESS);
        } else return new Result(ResultCode.FAIL);
    }


    public Result addPhone(String phone, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Login login = loginDao.getLoginByUserIdAndLoginType(user.getUserId(), "phone");
        if (login != null) {
            login.setIdentity(phone);
            loginDao.save(login);
        } else {
            login.setUserId(user.getUserId());
            login.setLoginType("phone");
            login.setIdentity(phone);
            loginDao.save(login);
        }
        return new Result(ResultCode.SUCCESS);
    }


    public String githubLogin(String code) throws IOException {
        String url = "https://github.com/login/oauth/access_token?" +
                "client_id=" + AuthUtils.CLIENT_ID +
                "&client_secret=" + AuthUtils.CLIENT_SECRET +
                "&code=" + code;
        String result = AuthUtils.doGetStr(url);
        String access_token = result.split("&")[0];
        String infoUrl = "https://api.github.com/user?" + access_token;
        JSONObject userInfo = AuthUtils.doGetJson(infoUrl);
        return userInfo.getString("id");
    }

    public ModelAndView githubJudge(String identity, HttpSession session, String loginType, Model model) {
        User user = (User) session.getAttribute("user");
        Login login = loginDao.findByIdentity(identity);
        if (identity == null) {
            return new ModelAndView("redirect:/moyue/user/index");}
        else if (login != null && user == null) {
            this.insideLogin(login,session);
            return new ModelAndView("redirect:/moyue/user/index");
        } else if (login == null && user != null) {
            Login login1 = new Login(loginDao.count(), user.getUserId(), loginType, identity, null);
            loginDao.save(login1);
            model.addAttribute("message", "绑定成功！");
            return new ModelAndView("safety-home");
        } else if (login == null && user == null) {
            model.addAttribute("github", identity);
            return new ModelAndView("redirect:/moyue/user/registerUI");
        } else{
            return new ModelAndView("redirect:/moyue/user/index");}
    }

    public Result showLoginMessage(HttpSession session) {
        User user = (User) session.getAttribute("user");
        List<Login> logins = loginDao.findByUserId(user.getUserId());
        return new Result(ResultCode.SUCCESS, logins);
    }
}
